

function Heap( values ){
	
	var _array = values;
	
	this.heapify = function(){
		var count = _array.length;
		var start = ( count - 2 ) >> 1;
		while ( start >= 0 ){
			this.siftDown( start, (count - 1));
			start--;
		}
		return _array;
	}
	
	
	this.siftDown = function( begin, end ){
		var root = begin;
		while ( ( root << 1 ) + 1 <= end ){
			var left = Math.floor( root << 1) + 1;
			var right = left + 1;
			var swap = root;
			if ( _array[swap] < _array[left] ){
				swap = left;
			}
			if ( (right <= end) && _array[swap] < _array[right]){
				swap = right;
			}
			if ( swap != root ){
				_array.swap(root, swap);
				root = swap;
			} else {
				return;
			}
		}
		
	}
	
	this.sort = function( count ){
		var last = count - 1;
		while ( last > 0 ){
			_array.swap(0, last);
			last--;
			this.siftDown(0, last);
		}
		return _array;
	}
}

